package de.dhbw.ka.tit09.picsim;

/**
 * Helper class for bit manipulation operations with integers.
 * 
 * @author Andreas Bender
 * 
 */
public abstract class BitUtility {
	/**
	 * Modifies a bit in an an integer at a given position.
	 * 
	 * @param value the integer that should be modified
	 * @param position the position of the bit to modify
	 * @param bit the boolean value of the bit
	 * @return the modified int value
	 */
	public static int getBitModifiedInt(int value, int position, boolean bit) {
		if (bit) {
			return value | (int) Math.pow(2, position);
		} else {
			return value & (Integer.MAX_VALUE - (int) Math.pow(2, position));
		}
	}

	/**
	 * Returns the boolean value of a bit at a specified position in an integer.
	 * 
	 * @param value the integer value
	 * @param position the bit position
	 * @return the boolean value of the bit
	 */
	public static boolean getBitValueFromInt(int value, int position) {
		return (value >>> position & 1) == 0 ? false : true;
	}

	/**
	 * Returns the dual value of a bit range in an integer.
	 * 
	 * @param value the integer
	 * @param lowestBit index of the lowest bit
	 * @param highestBit index of the highest bit
	 * @return the value of the bits
	 */
	public static int getValueInRange(int value, int lowestBit, int highestBit) {
		return (value >>> lowestBit)
				& ((int) Math.pow(2, highestBit - lowestBit + 1) - 1);
	}
}
